package middleware

import (
	"WchimeGinSystem/models"
	"WchimeGinSystem/utils"
	"WchimeGinSystem/utils/errmsg"
	jwtauth "WchimeGinSystem/utils/jwtAuth"

	"github.com/gin-gonic/gin"
)

func SuperAdminAuth() gin.HandlerFunc {

	return func(ctx *gin.Context) {
		cursor_user, _ := ctx.Get("user")
		claims, ok := cursor_user.(*jwtauth.MyClaims)
		if !ok {
			utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_BASE, "")
			ctx.Abort()
			return
		}
		user_id := claims.UserId

		user := get_user_instance(int(user_id))

		if user.Superadmin == 0 {
			utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_NOT_PERMISION, "")
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}

func get_user_instance(user_id int) models.User {

	var user models.User
	_ = models.DB.Where("id = ?", user_id).First(&user)
	return user
}
